package com.zsx.shopping.user.interceptor;

import com.zsx.shopping.common.constant.ShoppingConstant;
import com.zsx.shopping.common.exception.UserNotLoginException;
import com.zsx.shopping.common.session.UserVO;
import org.springframework.stereotype.Component;
import org.springframework.web.servlet.HandlerInterceptor;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

@Component
public class LoginInterceptor implements HandlerInterceptor {

    public static final ThreadLocal<UserVO> loginUser = new ThreadLocal<>();

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        HttpSession session = request.getSession();
        UserVO userVO = (UserVO) session.getAttribute(ShoppingConstant.LOGIN_USER);
        if (userVO == null) {
            throw new UserNotLoginException();
        }
        loginUser.set(userVO);
        return true;
    }
}
